<template>
  <el-card shadow="always">
    <!---- -- -- -- 头部-- -- -- -- -- -- -->
    <div slot="header">
      <!-- 路径导航 -->
       <Breadcrumb/>
    </div>
    <!---- -- -- -- 内容区域-- -- -- -- -- -- -->
    <!-- 筛选区域 -->
    <div class="filter-box">
      <div class="lt"></div>
      <div class="rt">
        <el-button type="primary"
                   size="small"
                   icon="el-icon-plus">增加</el-button>
      </div>
    </div>
    <!-- 表格区域 -->
    <div class="table-box">
      <!-- 4.渲染表格 -->
      <el-table :data="list"
                border>、
        <!-- 折叠列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <template v-if="scope.row.children.length">
              <el-row v-for="item in scope.row.children"
                      :key="item.id"
                      class="line-row">
                <el-col :span="6">
                  <el-tag type="primary">{{item.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="18">
                  <el-row v-for="val in item.children"
                          :key="val.id"
                          class="line-row no-pd">
                    <el-col :span="10">
                      <el-tag type="success">{{val.authName}}</el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="14">
                      <el-tag @close="delRoleAuth(scope.row,v.id)"
                              closable
                              v-for="v in val.children"
                              :key="v.id"
                              type="warning">{{v.authName}}</el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
            <template v-else>
              暂无数据信息
            </template>
          </template>
        </el-table-column>
        <el-table-column align="center"
                         type="index"
                         width="120"
                         label="序号"></el-table-column>
        <el-table-column align="center"
                         label="角色名称"
                         prop="roleName"></el-table-column>
        <el-table-column align="center"
                         label="角色描述"
                         prop="roleDesc"></el-table-column>
        <el-table-column align="center"
                         label="操作">
          <template slot-scope="scope">
            <el-button size="small"
                       type="success"
                       icon="el-icon-edit"
                       circle></el-button>
            <el-button size="small"
                       type="danger"
                       icon="el-icon-delete"
                       circle></el-button>
            <!-- 角色授权 -->
            <el-button size="small"
                       type="warning"
                       @click="setRoleAuth(scope.row)"
                       icon="el-icon-setting"
                       circle></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 角色授权弹框 -->
    <el-dialog title="角色授权"
               :visible.sync="isAuthShow"
               @close="defCheck=[]"
               width="30%">
      <!-- 操作遗留问题： 关闭弹框要将选中值的数组清空，每次都新盘子装数据！ 让树重新绘制，这样就不会有操作遗留 -->
      <el-tree node-key="id"
      ref="tree"
               v-if="isAuthShow"
               show-checkbox
               default-expand-all
               :default-checked-keys="defCheck"
               :props="{ children:'children',label:'authName' }"
               :data="allAuthList"></el-tree>
      <span slot="footer">
        <el-button @click="isAuthShow = false">关闭</el-button>
        <el-button type="primary" @click="isAuthSubmit">确定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
export default {
  name: 'Roles',
  data () {
    return {
      // 1. 列表变量
      list: [],
      // 角色授权弹框控制
      isAuthShow: false,
      // 所有权限列表数据(树形)
      allAuthList: [],
      defCheck: [], // 存储选中项的ID，(树形数据里面每个最底层的id)
      authRoleId: null // 授权的角色ID
    }
  },
  created () {
    // 3.调用方法
    this.getRoleList()
    // 获取所有权限列表数据
    this.getRightsList()
  },
  methods: {
    // 2.获取数据列表方法
    async getRoleList () {
      // 发送请求
      const { data: res } = await this.$axios.get('/roles')
      // 错误处理
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 成功赋值
      this.list = res.data
    },
    // 删除角色指定权限
    async delRoleAuth (row, rightId) {
      // row表示这一行的数据，rightId 表示点击的权限ID
      try {
        await this.$confirm('确定删除吗, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        // 发送请求
        const { data: res } = await this.$axios.delete('/roles/' + row.id + '/rights/' + rightId)
        // 错误处理
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        // 成功的更新视图
        row.children = res.data
      } catch (error) {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      }
    },
    // 获取所有权限列表数据(树形)
    async getRightsList () {
      const { data: res } = await this.$axios.get('/rights/tree') // 发请求
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg) // 错误处理
      this.allAuthList = res.data // 成功赋值
    },
    // 角色授权方法
    setRoleAuth (row) {
      // row.children 当前角色的权限
      this.getDefCheck(row, this.defCheck)
      this.isAuthShow = true
      this.authRoleId = row.id
    },
    // 递归方法用来获取权限最底层的id数据
    getDefCheck (row, arr) {
      // 如果这行没有了子级说明已经是最底层了
      if (!row.children || row.children.length === 0) {
        return arr.push(row.id)
      } else {
        // 还有子级
        row.children.forEach(val => {
          this.getDefCheck(val, arr)
        })
      }
    },
    // 角色树授权
    async isAuthSubmit () {
      // console.log(this.$refs.tree.getCheckedKeys()) // 打对钩的节点的ID
      // console.log(this.$refs.tree.getHalfCheckedKeys()) // 打横钩的节点的ID
      const rids = [...this.$refs.tree.getCheckedKeys(), ...this.$refs.tree.getHalfCheckedKeys()]
      if (!rids.length) return this.$message.warning('请勾选权限节点')
      const { data: res } = await this.$axios.post('/roles/' + this.authRoleId + '/rights', {
        rids: rids.join(',')
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.isAuthShow = false
      this.getRoleList()
    }
  }
}
</script>
<style scoped>
.line-row{
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
  display: flex;
  align-items: center;
}
.line-row:last-child{
  border:none;
}
.line-row .el-tag{
  margin-top: 10px;
  margin-right: 15px;
}
</style>
